package net.alche.fa.core.doing;
import net.alche.fa.core.model.Logic;
import net.alche.fa.core.model.FaValue;
import net.alche.fa.core.CodeLevel;
import net.alche.fa.core.SageStone;
import net.alche.fa.core.FaException;

//
// var
//
@FaAnnoDoing
public class SwitchDo extends AbstractDoing {

  @Override
  public boolean matched(String what, Logic g) {
    return "switch".equals(what);
  }

  @Override
  public FaValue doing(Logic g, CodeLevel lvl, SageStone st) throws FaException {
    // List<FaValue> params = super.getFaValueList(st, lvl, g)
    FaValue v = super.getLogicObjVal(st, lvl, g);
    boolean isDo = false;
    if (g.getChild() == null) {
      return null;
    }
    for (Logic logic: g.getChild()) {
      if (!isDo && "default".equals(logic.getWhat())) {
        isDo = true;
      }
      else {
        FaValue fav = super.getLogicObjVal(st, lvl, logic);
        if (IfDo.compare(fav, "==", v)) {
          isDo = true;
        }
      }
      if (isDo) {
        CodeLevel cl = lvl.instanceDeep();
        st.runCode(logic.getChild(), cl);
        if (cl.isBreak) {
          break;
        }
        else if ( cl.isReturn) {
          lvl.isReturn = true;
          lvl.returnObj = cl.returnObj;
          return lvl.returnObj;
        }
      }
    }
    lvl.doChild = false;
    return null;
  }
}